const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const session = require('express-session');
const bcrypt = require('bcrypt');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const db = require('./db');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// 配置中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static('public'));
app.use('/images', express.static(path.join(__dirname, '../images')));

// 视图引擎配置
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// 确保配置项之间有足够空间分隔不同功能区域

// 配置会话
app.use(session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

// 配置内存存储用于base64转换
const upload = multer({
    storage: multer.memoryStorage(),
    fileFilter: function (req, file, cb) {
        // 验证图片类型
        const filetypes = /jpeg|jpg|png|gif|webp/;
        const mimetype = filetypes.test(file.mimetype);
        const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
        
        if (mimetype && extname) {
            return cb(null, true);
        }
        cb(new Error('只允许上传图片文件 (JPG, JPEG, PNG, GIF, WebP)!'));
    },
    limits: {
        fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
    }
});

// 用户认证中间件
function isAuthenticated(req, res, next) {
    if (req.session.user) {
        return next();
    }
    res.redirect('/login');
}

// 管理员权限中间件
function isAdmin(req, res, next) {
    if (req.session.user && req.session.user.is_admin) {
        return next();
    }
    res.redirect('/');
}

// 路由
app.get('/', isAuthenticated, (req, res) => {
    res.render('chat', { user: req.session.user });
});

app.get('/login', (req, res) => {
    res.render('login');
});

app.post('/login', (req, res) => {
    const { username, password } = req.body;
    
    db.get('SELECT * FROM users WHERE username = ?', [username], (err, user) => {
        if (err || !user || !bcrypt.compareSync(password, user.password)) {
            return res.redirect('/login?error=Invalid credentials');
        }
        
        req.session.user = { id: user.id, username: user.username, is_admin: user.is_admin };
        res.redirect('/');
    });
});

app.post('/logout', (req, res) => {
    req.session.destroy();
    res.redirect('/login');
});

// 管理员路由
app.get('/admin', isAuthenticated, isAdmin, (req, res) => {
    db.all('SELECT * FROM users', (err, users) => {
        res.render('admin', { users, user: req.session.user, currentUser: req.session.user });
    });
});

app.post('/admin/add-user', isAuthenticated, isAdmin, (req, res) => {
    const { username, password, is_admin } = req.body;
    const hashedPassword = bcrypt.hashSync(password, 10);
    
    db.run(
        'INSERT INTO users (username, password, is_admin) VALUES (?, ?, ?)',
        [username, hashedPassword, is_admin ? 1 : 0],
        (err) => {
            if (err) {
                return res.redirect('/admin?error=' + encodeURIComponent(err.message));
            }
            res.redirect('/admin');
        }
    );
});

app.post('/admin/delete-user/:id', isAuthenticated, isAdmin, (req, res) => {
    const userId = req.params.id;
    
    // 不能删除自己
    if (userId == req.session.user.id) {
        return res.redirect('/admin?error=Cannot delete current user');
    }
    
    db.run('DELETE FROM users WHERE id = ?', [userId], (err) => {
        if (err) {
            return res.redirect('/admin?error=' + encodeURIComponent(err.message));
        }
        res.redirect('/admin');
    });
});

// 获取用户列表
app.get('/api/users', isAuthenticated, (req, res) => {
    db.all('SELECT id, username, is_admin FROM users WHERE id != ?', [req.session.user.id], (err, users) => {
        res.json(users);
    });
});

// 获取消息历史
app.get('/api/messages/:userId', isAuthenticated, (req, res) => {
    const currentUserId = req.session.user.id;
    const otherUserId = req.params.userId;
    
    db.all(
        `SELECT m.*, u.username as sender_name FROM messages m 
        JOIN users u ON m.sender_id = u.id 
        WHERE (m.sender_id = ? AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = ?) 
        ORDER BY m.created_at`,
        [currentUserId, otherUserId, otherUserId, currentUserId],
        (err, messages) => {
            res.json(messages);
        }
    );
});

// 上传图片并转换为base64
app.post('/api/upload-image', isAuthenticated, upload.single('image'), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ error: 'No file uploaded' });
    }
    
    try {
        // 将文件数据转换为base64
        const base64Data = req.file.buffer.toString('base64');
        // 创建完整的base64字符串，包含数据类型
        const dataUrl = `data:${req.file.mimetype};base64,${base64Data}`;
        
        res.json({ base64: dataUrl });
    } catch (error) {
        console.error('Error converting image to base64:', error);
        res.status(500).json({ error: 'Failed to process image' });
    }
});

// Socket.IO 连接管理
const activeUsers = {};

io.on('connection', (socket) => {
    console.log('New user connected');
    
    // 用户登录到Socket
    socket.on('login', (userId) => {
        activeUsers[userId] = socket.id;
        socket.userId = userId;
        console.log(`User ${userId} logged in`);
        
        // 通知其他用户该用户上线
        socket.broadcast.emit('user-online', userId);
    });
    
    // 发送消息
    socket.on('send-message', (data) => {
        const { receiver_id, content, message_type } = data;
        const sender_id = socket.userId;
        
        // 保存消息到数据库
        db.run(
            'INSERT INTO messages (sender_id, receiver_id, content, message_type) VALUES (?, ?, ?, ?)',
            [sender_id, receiver_id, content, message_type || 'text'],
            function(err) {
                if (err) {
                    console.error('Error saving message:', err);
                    return;
                }
                
                // 获取消息详情
                db.get(
                    `SELECT m.*, u.username as sender_name FROM messages m 
                    JOIN users u ON m.sender_id = u.id 
                    WHERE m.id = ?`,
                    [this.lastID],
                    (err, message) => {
                        if (err) {
                            console.error('Error retrieving message:', err);
                            return;
                        }
                        
                        // 发送给接收者（如果在线）
                        if (activeUsers[receiver_id]) {
                            io.to(activeUsers[receiver_id]).emit('receive-message', message);
                        }
                        
                        // 发送给发送者
                        socket.emit('receive-message', message);
                    }
                );
            }
        );
    });
    
    // 断开连接
    socket.on('disconnect', () => {
        const userId = socket.userId;
        if (userId) {
            delete activeUsers[userId];
            console.log(`User ${userId} disconnected`);
            
            // 通知其他用户该用户下线
            socket.broadcast.emit('user-offline', userId);
        }
    });
    
    // 获取在线用户列表
    socket.on('get-active-users', () => {
        socket.emit('active-users', Object.keys(activeUsers));
    });
});

// 提供上传文件的静态访问 - 使用绝对路径
app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
    maxAge: '1d',
    setHeaders: function (res, path) {
        // 设置适当的MIME类型头
        res.setHeader('Cache-Control', 'public, max-age=86400');
    }
}));

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});